package client.backend.price;

import java.util.HashMap;
import java.util.StringTokenizer;

import server.conn.ConnectionThread;
import server.conn.user.UserConnectionThread;
import client.backend.Connection;

/**
 * Stores information about all of the different prices.
 *
 */
public class PriceController {
	private String[] currs;
	private String[] currPairs;
	private HashMap<String, Price> prices;
	private PricesThread pricesThread;
	
	/**
	 * Private constructor.
	 */
	private PriceController() {
		prices = new HashMap<String, Price>();
		
		setCurrs();
		setCurrPairs();
		initializePrices();
		
		pricesThread = new PricesThread(6000);
		pricesThread.start();
	}
	
	/**
	 * Private method for getting currencies from server.
	 */
	private void setCurrs() {
		currs = Connection.getInstance().readArray(UserConnectionThread.PRICE_GET_CURRENCIES+"");			
	}
	
	/**
	 * Organizes currencies into pairs.
	 */
	private void setCurrPairs() {
		currPairs = new String[((currs.length) * (currs.length - 1)) / 2];
		int counter = 0;
		
		for (int x = 0; x < currs.length - 1; x++) {
			for (int y = x + 1; y < currs.length; y++) {
				currPairs[counter++] = currs[x] + currs[y];
			}
		}
	}
	
	/**
	 * Private method for initializing the price of each currency.
	 */
	private void initializePrices() {
		if (currs != null) {
			for (String cur1 : currs) {
				for (String cur2 : currs) {
					if (!cur1.equals(cur2)) {
						prices.put(cur1+cur2, new Price(cur1,cur2));
					}
				}
			}
		}
	}
	
	/**
	 * Gets price ratio of two currencies.
	 * @param cur1	First currency.
	 * @param cur2	Second currency.
	 * @return		Price object for given ratio.
	 */
	public Price getPrice(String cur1, String cur2) {
		return (prices.containsKey(cur1+cur2)) ? prices.get(cur1+cur2) : null;
	}
	
	/**
	 * Updates prices using an input string.
	 * @param input	String used containing price information.
	 */
	protected void updatePrices(String input) {
		StringTokenizer strTok = new StringTokenizer(input, ConnectionThread.SPLIT);
		
		prices.get(strTok.nextToken()+strTok.nextToken()).updatePrice(new Float(strTok.nextToken()), new Float(strTok.nextToken()), new Long(strTok.nextToken()));
	}
	
	/**
	 * Getter method for currencies.
	 * @return	Array of currencies.
	 */
	public String[] getCurrs() { return currs; }
	
	/**
	 * Getter method for currency pairs.
	 * @return	Array of currency pairs.
	 */
	public String[] getCurrPairs() { return currPairs; }
	
	/**
	 * Holds ono PriceController instance.
	 *
	 */
	private static class PriceControllerHolder { 
		private final static PriceController INSTANCE = new PriceController();
	}
 
	/**
	 * Returns the singleton instance of PriceController.
	 * @return	Singleton instance.
	 */
	public static PriceController getInstance() {
		return PriceControllerHolder.INSTANCE;
	}
}
